package com.aids_malaria.ui.datacollect;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import com.aids_malaria.R;
import com.aids_malaria.adapter.MosquitoBorneDataAdapter;
import com.aids_malaria.app.Constant;
import com.aids_malaria.base.BaseActivity;
import com.aids_malaria.base.BaseQuickAdapter;
import com.aids_malaria.db.DBManager;
import com.aids_malaria.event.Events;
import com.aids_malaria.helper.PointLengthFilter;
import com.aids_malaria.http.BaseObserver;
import com.aids_malaria.http.RetrofitFactory;
import com.aids_malaria.http.RxScheduler;
import com.aids_malaria.http.api.RetrofitApi;
import com.aids_malaria.http.response.AreaC;
import com.aids_malaria.http.response.AreaV;
import com.aids_malaria.http.response.MosquitoInvest;
import com.aids_malaria.util.AuthUtil;
import com.aids_malaria.util.DateUtil;
import com.aids_malaria.util.GsonUtil;
import com.aids_malaria.util.LogUtil;
import com.aids_malaria.util.ResourceUtil;
import com.aids_malaria.util.StringUtil;
import com.aids_malaria.util.ToastUtil;
import com.aids_malaria.widget.dialog.NumDialog;
import com.aids_malaria.widget.titlebar.TitleBar;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.luck.picture.lib.rxbus2.Subscribe;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class MosquitoBorneDataActivity extends BaseActivity {

    @BindView(R.id.title_bar)
    TitleBar title_bar;
    @BindView(R.id.et_county_name)
    TextView et_county_name;
    @BindView(R.id.et_village_name)
    TextView et_village_name;
    @BindView(R.id.et_record_num)
    TextView et_record_num;
    @BindView(R.id.et_coordinate_x)
    EditText et_coordinate_x;
    @BindView(R.id.et_coordinate_y)
    EditText et_coordinate_y;
    @BindView(R.id.et_detail_place)
    EditText et_detail_place;
    @BindView(R.id.et_inquire_people)
    EditText et_inquire_people;
    @BindView(R.id.et_inquire_time)
    TextView et_inquire_time;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refresh_layout;
    @BindView(R.id.rv_data)
    RecyclerView rv_data;

    private List<MosquitoInvest> mData = new ArrayList<>();
    private MosquitoBorneDataAdapter mosquitoBorneDataAdapter;

    private MosquitoInvest mMosquitoInvest;
    private String county_code;
    private String village_code;
    private String area_code;
    private String record_seq;
    private int maxNum = 0;

    private boolean isHasNoData = false;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_mosquito_borne_data;
    }

    @Override
    protected void initView() {
        super.initView();
        initTitleBar(title_bar, ResourceUtil.getString(R.string.mosquito_borne_data_collect));
        initRefreshLayout();

        PointLengthFilter pointLengthFilter = new PointLengthFilter(6);
        et_coordinate_x.setFilters(new InputFilter[]{pointLengthFilter});
        et_coordinate_y.setFilters(new InputFilter[]{pointLengthFilter});

        et_coordinate_x.setInputType(InputType.TYPE_CLASS_NUMBER|InputType.TYPE_NUMBER_FLAG_DECIMAL);
        et_coordinate_y.setInputType(InputType.TYPE_CLASS_NUMBER|InputType.TYPE_NUMBER_FLAG_DECIMAL);
    }

    @Override
    protected void initData() {
        super.initData();
        initRecycleView();
        record_seq = "";
        et_record_num.setText(record_seq);
    }

    private void initRefreshLayout() {
        refresh_layout.setEnableLoadMore(false);
        refresh_layout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                refresh_layout.finishLoadMore(1500);
                getMosquitoInvest();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refresh_layout.finishRefresh(1000);
                getMosquitoInvest();
            }
        });


        et_coordinate_x.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
        et_coordinate_y.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
    }

    private void initRecycleView() {
        rv_data.setLayoutManager(new LinearLayoutManager(mContext));
        mosquitoBorneDataAdapter = new MosquitoBorneDataAdapter(mContext,R.layout.item_mosquito_borne_data,mData);
        rv_data.setAdapter(mosquitoBorneDataAdapter);
        mosquitoBorneDataAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (!AuthUtil.isHaveUpdateAuthByCode(Constant.COLLECT_MOSQUITO_BORNE)){
                    ToastUtil.showNoPermission();
                    return;
                }
                Bundle bundle = new Bundle();
                MosquitoInvest mosquitoInvest = mData.get(position);
                String x =  et_coordinate_x.getText().toString().trim();
                String y =  et_coordinate_y.getText().toString().trim();
                mosquitoInvest.setX(Float.parseFloat(x.length() > 0 ? x : "0.0" ));
                mosquitoInvest.setY(Float.parseFloat(y.length() > 0 ? y : "0.0" ));
                mosquitoInvest.setInvest_place(et_detail_place.getText().toString().trim());
                mosquitoInvest.setInvestor(et_inquire_people.getText().toString().trim());
                mosquitoInvest.setInvest_time(et_inquire_time.getText().toString().trim());
                bundle.putSerializable(MosquitoBorneDataEditActivity.KEY_MOSQUITO_INVEST,mData.get(position));
                bundle.putBoolean(MosquitoBorneDataEditActivity.KEY_IS_CREATE,isHasNoData);
                startActivityForResult(MosquitoBorneDataEditActivity.class,200,bundle);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 200){
            refresh_layout.autoRefresh();
            getMosquitoInvest();
        }

    }

    @OnClick({R.id.iv_county_select,R.id.iv_village_select,R.id.iv_record_num_select,R.id.iv_record_num_add,
            R.id.tv_gain_coordinate,R.id.et_county_name,R.id.et_village_name,R.id.et_record_num,R.id.iv_inquire_time_select,R.id.et_inquire_time})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.iv_county_select:
            case R.id.et_county_name:
                //县选择
                startActivity(CountySelectActivity.class);
                break;
            case R.id.iv_village_select:
            case R.id.et_village_name:
                //村选择
                Bundle bundle = new Bundle();
                bundle.putString("county_code",county_code);
                bundle.putString("county_name",et_county_name.getText().toString().trim());
                startActivity(VillageSelectActivity.class,bundle);
                break;
            case R.id.iv_record_num_select:
            case R.id.et_record_num:
                numSub(et_record_num);
                break;
            case R.id.iv_record_num_add:
                numAdd(et_record_num);
                break;
            case R.id.tv_gain_coordinate:
                //获取定位
                getLocation();
//                getMosquitoInvest();
                break;
            case R.id.iv_inquire_time_select:
            case R.id.et_inquire_time:
                DateUtil.newTimeSelect(this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        et_inquire_time.setText(DateUtil.getFullTimeFormatter().format(date));
                    }
                }).show();
                break;
        }
    }
    private String provider = "";
    private LocationListener locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            getLoadingDialog().dismiss();
            et_coordinate_x.setText(String.format("%.6f", location.getLongitude()) + "");
            et_coordinate_y.setText(String.format("%.6f", location.getLatitude()) + "");
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {
            getLoadingDialog().dismiss();

        }

        @Override
        public void onProviderEnabled(String s) {
            getLoadingDialog().dismiss();
        }

        @Override
        public void onProviderDisabled(String s) {
            getLoadingDialog().dismiss();
        }
    };

    /**
     * 获取定位
     */
    @SuppressLint("MissingPermission")
    private void getLocation() {
        getLoadingDialog().show();
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        //获取所有可用的位置提供器
        List<String> providerList = locationManager.getProviders(true);
        if (providerList.contains(LocationManager.GPS_PROVIDER)) {
            provider = LocationManager.GPS_PROVIDER;
        } else if (providerList.contains(LocationManager.NETWORK_PROVIDER)) {
            provider = LocationManager.NETWORK_PROVIDER;
        } else {
            ToastUtil.showToast("No location provider to use");
        }
        Location location = locationManager.getLastKnownLocation(provider);
        if(location !=null){
            getLoadingDialog().dismiss();
            et_coordinate_x.setText(String.format("%.6f", location.getLongitude()) + "");
            et_coordinate_y.setText(String.format("%.6f", location.getLatitude()) + "");
        }
        locationManager.requestLocationUpdates(provider, 5000, 1, locationListener);
    }

    /**
     * 序号减
     * @param editText
     */
    private void numSub(TextView editText){
        new NumDialog(mContext, maxNum,new NumDialog.OnNumClickListener() {
            @Override
            public void onNumClick(int num, Dialog dialog) {
                editText.setText(num + "");
                record_seq = num + "";
                dialog.dismiss();
                getMosquitoInvest();
            }
        }).show();
    }

    /**
     * 序号加
     * @param editText
     */
    private void numAdd(TextView editText){
        String strNum = editText.getText().toString().trim();
        if (TextUtils.isEmpty(strNum)){
            return;
        }
        try{
            int num = Integer.parseInt(strNum) + 1;
            editText.setText("" + num);
            record_seq = num + "";
            getMosquitoInvest();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 县选择回调
     * @param countySelectEvent
     */
    @Subscribe
    public void onCodeEvent(Events.CountySelectEvent countySelectEvent){
        //重新选择县后，后面的村最好置空，数据也同样置空
        AreaC areaC = countySelectEvent.getAreaC();
        if (!areaC.getCounty_code().equals(county_code)){
            et_village_name.setText("");
            et_record_num.setText("");
            village_code = "";
            area_code = "";
            clearData();
            county_code = areaC.getCounty_code();
            et_county_name.setText(areaC.getCounty_name());
//            getMosquitoInvest();
        }
    }

    /**
     * 村选择回调
     * @param villageSelectEvent
     */
    @Subscribe
    public void onCodeEvent(Events.VillageSelectEvent villageSelectEvent){
        AreaV areaV = villageSelectEvent.getAreaV();
        if (!areaV.getVillage_code().equals(village_code)){
            clearData();
            village_code = areaV.getVillage_code();
            et_village_name.setText(areaV.getVillage_name());
            area_code = areaV.getVillage_code();
            getMosquitoInvest();
        }

    }

    private void clearData(){
        maxNum = 0;
        record_seq = "";
        et_record_num.setText("");
        mData.clear();
        et_coordinate_x.setText("");
        et_coordinate_y.setText("");
        mosquitoBorneDataAdapter.notifyDataSetChanged();
        et_detail_place.setText("");
        et_inquire_people.setText("");
        et_inquire_time.setText("");
    }



    /**
     * 获取蚊媒数据
     */
    private void getMosquitoInvest(){
        if(StringUtil.isEmpty(area_code) ){
            return;
        }
        if (!AuthUtil.isHaveQueryAuthByCode(Constant.COLLECT_MOSQUITO_BORNE)){
            ToastUtil.showNoPermission();
            return;
        }
        if(isOnLine()){
            RetrofitFactory.getInstance().createApi(RetrofitApi .class).getMosquitoInvest(area_code,record_seq)
                    .compose(RxScheduler.rxSchedulerTransform())
                    .subscribe(new BaseObserver<List<MosquitoInvest>>() {

                        @Override
                        protected void onStart() {
                            getLoadingDialog().show();
                        }

                        @Override
                        protected void onSuccess(List<MosquitoInvest> data) throws Exception {
                            List<Integer> recordNoList = new ArrayList<>();
                            for (MosquitoInvest item : data) {
                                recordNoList.add(item.getRecord_seq());
                            }
                            if (StringUtil.isEmpty(record_seq)){
                                if(recordNoList.size()>0){
                                    maxNum = Collections.max(recordNoList);
                                }else{
                                    maxNum = 0;
                                }
                            }

                            if (StringUtil.isEmpty(record_seq)){
                                return;
                            }
                            if (data != null && data.size()>0) {
                                isHasNoData = false;
                                mMosquitoInvest = data.get(0);
                            }else{
                                isHasNoData = true;
                                mMosquitoInvest = new MosquitoInvest();
                                mMosquitoInvest.setAedes_bit_rate(0);
                                mMosquitoInvest.setAedes_density(0);
                                mMosquitoInvest.setAedes_infect_rate(0);
                                mMosquitoInvest.setAnopheles_bit_rate(0);
                                mMosquitoInvest.setAnopheles_density(0);
                                mMosquitoInvest.setAnopheles_infect_rate(0);
                                mMosquitoInvest.setCreating_time("");
                                mMosquitoInvest.setCreator("");
                                mMosquitoInvest.setCulex_bit_rate(0);
                                mMosquitoInvest.setCulex_density(0);
                                mMosquitoInvest.setCulex_infect_rate(0);
                                mMosquitoInvest.setInvest_place("");
                                mMosquitoInvest.setInvest_time("");
                                mMosquitoInvest.setInvestor("");
                                mMosquitoInvest.setOther_bit_rate(0);
                                mMosquitoInvest.setOther_density(0);
                                mMosquitoInvest.setOther_infect_rate(0);

                                mMosquitoInvest.setRecord_seq(Integer.valueOf(record_seq));

                                mMosquitoInvest.setUpdate_time("");
                                mMosquitoInvest.setUpdator("");
                                mMosquitoInvest.setX(0);
                                mMosquitoInvest.setY(0);
                                mMosquitoInvest.setInvest_area_code(area_code);
                            }
                            et_coordinate_x.setText(mMosquitoInvest.getX() + "");
                            et_coordinate_y.setText(mMosquitoInvest.getY() + "");
                            et_detail_place.setText(mMosquitoInvest.getInvest_place());
                            et_inquire_people.setText(mMosquitoInvest.getInvestor());
                            et_inquire_time.setText(mMosquitoInvest.getInvest_time());

                            //构建数据
                            MosquitoInvest mosquitoInvestItem1 = MosquitoInvest.copyToItem(mMosquitoInvest);
                            mosquitoInvestItem1.setSortType(MosquitoInvest.SORT_TYPE_AEDES);

                            MosquitoInvest mosquitoInvestItem2 = MosquitoInvest.copyToItem(mMosquitoInvest);
                            mosquitoInvestItem2.setSortType(MosquitoInvest.SORT_TYPE_ANOPHELES);

                            MosquitoInvest mosquitoInvestItem3 = MosquitoInvest.copyToItem(mMosquitoInvest);
                            mosquitoInvestItem3.setSortType(MosquitoInvest.SORT_TYPE_CULEX);

                            MosquitoInvest mosquitoInvestItem4 = MosquitoInvest.copyToItem(mMosquitoInvest);
                            mosquitoInvestItem4.setSortType(MosquitoInvest.SORT_TYPE_OTHER);
                            mosquitoInvestItem4.setInvest_area_code(area_code);

                            mData.clear();
                            mData.add(mosquitoInvestItem1);
                            mData.add(mosquitoInvestItem2);
                            mData.add(mosquitoInvestItem3);
                            mData.add(mosquitoInvestItem4);
                            LogUtil.d("mData:"+GsonUtil.beanToJson(mData));
                            mosquitoBorneDataAdapter.notifyDataSetChanged();
                        }

                        @Override
                        protected void onFinish() {
                            getLoadingDialog().dismiss();
                        }
                    });
        }else{
            List<MosquitoInvest> mosquitoInvestList = new ArrayList<>();
            if(!StringUtil.isEmpty(record_seq)){
                mosquitoInvestList.addAll(DBManager.get().mosquitoInvestDao().findByAreaCode(
                        area_code,Integer.parseInt(record_seq)));
            }else{
                mosquitoInvestList.addAll(DBManager.get().mosquitoInvestDao().findByCode(area_code));
            }
            List<Integer> recordNoList = new ArrayList<>();
            for (MosquitoInvest item : mosquitoInvestList) {
                recordNoList.add(item.getRecord_seq());
            }
            if (StringUtil.isEmpty(record_seq)){
                if(recordNoList.size()>0){
                    maxNum = Collections.max(recordNoList);
                }else{
                    maxNum = 0;
                }
            }
            if (StringUtil.isEmpty(record_seq)){
                return;
            }
            LogUtil.d("mosquitoInvestList:"+ GsonUtil.beanToJson(mosquitoInvestList));
            if (mosquitoInvestList == null || mosquitoInvestList.size() ==0) {
                isHasNoData = true;
                mMosquitoInvest = new MosquitoInvest();
                mMosquitoInvest.setAedes_bit_rate(0);
                mMosquitoInvest.setAedes_density(0);
                mMosquitoInvest.setAedes_infect_rate(0);
                mMosquitoInvest.setAnopheles_bit_rate(0);
                mMosquitoInvest.setAnopheles_density(0);
                mMosquitoInvest.setAnopheles_infect_rate(0);
                mMosquitoInvest.setCreating_time("");
                mMosquitoInvest.setCreator("");
                mMosquitoInvest.setCulex_bit_rate(0);
                mMosquitoInvest.setCulex_density(0);
                mMosquitoInvest.setCulex_infect_rate(0);
                mMosquitoInvest.setInvest_area_code("");
                mMosquitoInvest.setInvest_place("");
                mMosquitoInvest.setInvest_time("");
                mMosquitoInvest.setInvestor("");
                mMosquitoInvest.setOther_bit_rate(0);
                mMosquitoInvest.setOther_density(0);
                mMosquitoInvest.setOther_infect_rate(0);

                mMosquitoInvest.setRecord_seq(Integer.valueOf(record_seq));

                mMosquitoInvest.setUpdate_time("");
                mMosquitoInvest.setUpdator("");
                mMosquitoInvest.setX(0);
                mMosquitoInvest.setY(0);
                mMosquitoInvest.setInvest_area_code(area_code);
            }else{
                isHasNoData = false;
                mMosquitoInvest = mosquitoInvestList.get(0);
            }
            et_coordinate_x.setText(mMosquitoInvest.getX() + "");
            et_coordinate_y.setText(mMosquitoInvest.getY() + "");
            et_detail_place.setText(mMosquitoInvest.getInvest_place());
            et_inquire_people.setText(mMosquitoInvest.getInvestor());
            et_inquire_time.setText(mMosquitoInvest.getInvest_time());

            //构建数据
            MosquitoInvest mosquitoInvestItem1 = MosquitoInvest.copyToItem(mMosquitoInvest);
            mosquitoInvestItem1.setSortType(MosquitoInvest.SORT_TYPE_AEDES);

            MosquitoInvest mosquitoInvestItem2 = MosquitoInvest.copyToItem(mMosquitoInvest);
            mosquitoInvestItem2.setSortType(MosquitoInvest.SORT_TYPE_ANOPHELES);

            MosquitoInvest mosquitoInvestItem3 = MosquitoInvest.copyToItem(mMosquitoInvest);
            mosquitoInvestItem3.setSortType(MosquitoInvest.SORT_TYPE_CULEX);

            MosquitoInvest mosquitoInvestItem4 = MosquitoInvest.copyToItem(mMosquitoInvest);
            mosquitoInvestItem4.setSortType(MosquitoInvest.SORT_TYPE_OTHER);

            mData.clear();
            mData.add(mosquitoInvestItem1);
            mData.add(mosquitoInvestItem2);
            mData.add(mosquitoInvestItem3);
            mData.add(mosquitoInvestItem4);
            mosquitoBorneDataAdapter.notifyDataSetChanged();
        }
    }

    private void getMaxNum(){

    }

}
